<?php

namespace app\admin\model;

class Classroom extends Commonmodel {

    protected $gradeTable;
    protected $typeTable;

    public function __construct(array $data = [])
    {
        $this->table = 'zhjs_classroom';
        $this->pk = 'id';
        parent::__construct($data);
        $this->typeTable = 'zhjs_classroom_type';
        $this->gradeTable = 'zhjs_classroom_grade';
    }

    public function findAll($where = null, $pageParam = null, $num = 20){
        $whereData = [['c.is_delete' , '=', 1]];
        $paginate = ['list_rows'=>$num];
        if($where)  $whereData = array_merge($where, $whereData);
        if($pageParam = array_splice($pageParam, 1))  $paginate = array_merge($paginate, ['query'=>$pageParam]);

        $data = self::db()
            ->alias('c')
            ->join([$this->typeTable=>'t'],'c.type=t.id')
            ->join([$this->gradeTable=>'g'],'c.level=g.id')
            ->field('c.id, c.name, t.name as typename, g.name as gradename, codekey, adress, c.create_date, c.status, date_format(end_time, "%Y-%m-%d") as end_time,  date_format(start_time, "%Y-%m-%d") as start_time')
            ->where($whereData)
            ->order(['c.id'=>'desc'])
            ->paginate($paginate);

        if(!$data)  return false;

        $list['page'] = $data->render();
        $dataArr = $data->toArray();
        $list['data'] = $dataArr['data'];

        return $list;
    }

    /**
     * 保存
     * @param $data
     * @param null $id
     * @return bool|string
     */
    public function saveInfo($data, $id = null){

        if(!$data)  return false;

        if(!$id){
            $data['uid'] = session('adminUserInfo.uid');
            $data['codekey'] = $this->getCodeKey();
            $data['create_date'] = date("Y-m-d H:i:s", time());
        }

        $res = parent::saveDataInfo($data, $id);

        if(!$res)  return false;
        return $res;
    }

    public function getCodeKey($codekey = null){
        if($codekey){
            $res = self::db()->field('id')->where(['codekey'=>$codekey])->find();
            if($res)  return $this->getCodeKey();
            return $codekey;
        }else{
            $codekey = time() . rand(10000, 99999);
            return $this->getCodeKey($codekey);
        }
    }

}

?>